package com.sunwayworld.basemodule.framework;

import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import com.sunwayworld.framework.exception.core.HttpErrorMessage;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.log.annotation.Log;
import com.sunwayworld.framework.log.annotation.LogType;
import com.sunwayworld.framework.utils.ServletUtils;
import com.sunwayworld.framework.utils.StringUtils;
import io.sentry.Sentry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@ControllerAdvice
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LimsGlobalExceptionHandler {
    private static final Logger logger = LogManager.getLogger(LimsGlobalExceptionHandler.class);

    @Value("${sentry.enabled}")
    private boolean sentryEnable;

    @Deprecated
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @Log(value = "数据库字段长度异常", type = LogType.EXCEPTION)
    public void handleMysqlDataTruncation(MysqlDataTruncation dataTruncation) {
        if(sentryEnable){
            Sentry.captureException(dataTruncation);
        }

        String message = dataTruncation.getMessage();
        String info = I18nHelper.getMessage("GIKAM.EXCEPTION.UNEXPECTED");
        if (StringUtils.containsIgnoreCase(message, "Data too long")) {
            info = I18nHelper.getMessage("JDBC_EXCEPTIONS.DATA_TRUNCATION") + "<br/>" + message.split(":")[1];
        }
        ServletUtils.responseError(HttpErrorMessage.of(HttpStatus.BAD_REQUEST, info));
    }

}